<template>
  <div class="full-box shadow-box padding-box">
    <OperateCommon
      :showSave="true"
      :showBack="true"
      @save="save"
      @back="linkTo('/roleList')"
    >
    </OperateCommon>
    <div class="c-form-padding">
      <el-form
        class="c-form"
        :model="form"
        ref="form"
        :rules="rules"
        label-width="80px"
        :inline="false"
      >
        <el-form-item label="角色名称" prop="role_name">
          <el-input v-model="form.role_name" placeholder=""></el-input>
        </el-form-item>
        <el-form-item label="排序" prop="">
          <el-input-number
            v-model="form.sort"
            label=""
            :step="1"
            :controls="true"
            controls-position="right"
          >
          </el-input-number>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            type="textarea"
            v-model="form.remark"
            placeholder=""
            :autosize="{
              minRows: 3,
              maxRows: 6,
            }"
          ></el-input>
        </el-form-item>
      </el-form>
      <div class="role-content">
        <div class="menu">
          <div class="title">菜单权限</div>
          <el-tree
            ref="tree"
            node-key="id"
            default-expand-all
            empty-text=""
            :show-checkbox="true"
            :highlight-current="true"
            :data="menuTree"
            :default-checked-keys="form.menu"
            :props="{
              label: 'menu_name',
            }"
          ></el-tree>
        </div>
        <div class="permiss">
          <div class="title">按钮权限</div>
          <el-collapse v-model="activeNames">
            <el-collapse-item
              v-for="(item, index) in permissTree"
              :key="index"
              :title="item.name"
              :name="item.name"
            >
              <div>
                <el-checkbox
                  v-for="(permiss, index) in item.value"
                  :key="index"
                  v-model="permiss.checked"
                  >{{ permiss.permission_name }}</el-checkbox
                >
              </div>
            </el-collapse-item>
          </el-collapse>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import OperateCommon from "@/components/Common/OperateCommon.vue";
import LinkTo from "@/mixins/LinkTo";
import { required } from "@/utils/eValidate";
import { getMenuTree } from "@/api/System/Menu";
import { getPermissTree } from "@/api/System/Permiss";
import { getRoleDetials, saveRole } from "@/api/System/Role";
export default {
  name: "Role",
  mixins: [LinkTo],
  components: { OperateCommon },
  data() {
    return {
      id: 0,
      form: {
        role_name: "",
        sort: "",
        remark: "",
        menu: [],
        permission: [],
      },
      rules: {
        user_code: [required],
        user_name: [required],
      },
      menuTree: [],
      permissTree: [],
      activeNames: [],
      menuPNodes: [],
    };
  },
  methods: {
    async initMenu() {
      await getMenuTree().then((res) => {
        if (res.code == 0) {
          this.menuTree = res.data;

          let deepNode = JSON.parse(JSON.stringify(res.data));

          this.menuPNodes = deepNode
            .map((i) => {
              return this.recursionPNodes(i);
            })
            .filter((i) => {
              return i != undefined;
            });
        }
      });
    },
    recursionPNodes(node) {
      if (node.children) {
        node.children = node.children.map((i) => {
          return this.recursionPNodes(node.children);
        });
        return node.id;
      }
    },
    async initPermiss() {
      await getPermissTree().then((res) => {
        if (res.code == 0) {
          this.permissTree = this.recursionPermiss(res.data);
        }
      });
    },
    recursionPermiss(arr) {
      return arr.map((i) => {
        if (i.value && i.value.length > 0) {
          i.value = this.recursionPermiss(i.value);
        } else {
          i.checked = false;
        }
        return i;
      });
    },
    initData() {
      getRoleDetials({ id: this.id }).then((res) => {
        if (res.code == 0) {
          this.form = res.data;

          let unincluePNode = this.form.menu.filter((i) => {
            if (this.menuPNodes.indexOf(i) == -1) {
              return i;
            }
          });

          this.form.menu = unincluePNode;

          this.checkPermiss(this.permissTree, this.form.permission);
        }
      });
    },
    checkPermiss(arr, checkArr) {
      return arr.map((i) => {
        if (i.value && i.value.length > 0) {
          i.value = this.checkPermiss(i.value, checkArr);
        } else {
          checkArr.map((c) => {
            if (i.id == c) {
              this.$set(i, "checked", true);
            }
          });
        }
        return i;
      });
    },
    recursionChecked(arr) {
      return arr.map((i) => {
        if (i.value && i.value.length > 0) {
          return this.recursionChecked(i.value);
        }
        if (i.checked) {
          return i.id;
        }
      });
    },
    save() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          let checked = this.recursionChecked(this.permissTree)
            .toString()
            .split(",")
            .filter((i) => {
              if (i) {
                return i;
              }
            });

          let halfCheck = JSON.parse(
            JSON.stringify(this.$refs.tree.getHalfCheckedKeys())
          );

          this.form.MenuPower = this.$refs.tree
            .getCheckedNodes()
            .map((i) => {
              return i.id;
            })
            .concat(halfCheck);

          this.form.PermsPower = checked;
          delete this.form.menu;
          delete this.form.permission;
          saveRole(this.form).then((res) => {
            if (res.code == 0) {
              this.$message.success("保存成功");
            }
          });
        }
      });
    },
    clearDefaultCheck() {
      this.$nextTick(() => {
        this.$refs.tree.setCheckedKeys([]);
      });
    },
  },
  created() {
    this.id = this.$route.params.id;
    Promise.all([this.initMenu(), this.initPermiss()]).then(() => {
      if (this.id > 0) {
        this.initData();
      }
    });
  },
};
</script>

<style lang="scss" scoped>
@import "@/assets/base-form.scss";
.role-content {
  width: 100%;
  display: flex;
  margin-top: 10px;
  > div {
    width: 50%;
    > .title {
      height: 30px;
      line-height: 30px;
      font-weight: 600;
      border-left: 5px solid $colorBlue;
      box-sizing: border-box;
      padding: 0 0 0 10px;
    }
  }
}
</style>
